package handler

import (
	"sept16-hw/model"
	"sept16-hw/pkg"
	"strconv"

	"github.com/gin-gonic/gin"
)

func Register(c *gin.Context) {
	phone := c.PostForm("phone")
	password := pkg.Md5(c.PostForm("password"))

	user := model.User{
		Phone:    phone,
		Password: password,
	}
	err := model.DB.Create(&user).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "注册失败",
		})
		return
	}

	if phone == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "手机号和密码不能为空",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "注册成功",
	})
	return
}

func Login(c *gin.Context) {
	phone := c.PostForm("phone")
	password := c.PostForm("password")

	var user model.User
	err := model.DB.Where("phone = ?", phone).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名不正确",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}

	if user.Password != pkg.Md5(password) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码不正确",
		})
		return
	}

	token := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": token,
	})
	return
}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")

	news := model.New{
		Title:   title,
		Content: content,
	}
	err := model.DB.Create(&news).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var news []*model.New
	model.DB.Offset(offset).Limit(size).Find(&news)

	var total int64
	model.DB.Model(&model.New{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表获取成功",
		"total": total,
		"data":  news,
	})
	return
}
